<template>
  <div class="categories">
    <div class="navigation">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>商品分类</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-card class="box-card">
      <div class="top">
        <div class="search-content">
          <el-input placeholder="请输入分类ID" v-model="searchInput"></el-input>
          <!-- <el-input placeholder="请输入内容" v-model="input2"></el-input> -->
          <el-button
            class="search-icon"
            type="primary"
            icon="el-icon-search"
            @click="search"
          ></el-button>
        </div>
        <div class="add-user">
          <el-button type="primary" @click="showAddDialog">添加分类</el-button>
        </div>
      </div>

      <template>
        <!-- selection-type 多选类型表格 布尔类型 -->
        <!-- expand-type 是否为展开类型表格 -->
        <!-- show-index  是否显示数据索引-->
        <!-- index-text 数据索引名称 -->
        <!-- show-row-hover 鼠标悬停时，当先行是否高亮 -->
        <tree-table
          :data="categoryList.result"
          border
          :columns="columns"
          :selection-type="false"
          :expand-type="false"
          :show-index="true"
          index-text="#"
          :show-row-hover="false"
        >
          <!-- <el-table-column label="#" type="index"></el-table-column> -->
          <!-- <el-table-column
            prop="cat_name"
            label="分类名称"
            width="200"
          ></el-table-column> -->
          <!-- <el-table-column prop="cat_deleted" label="是否有效" width="200"> -->
          <template slot-scope="scope" slot="isok">
            <i
              class="el-icon-success"
              style="color: lightgreen"
              v-if="scope.row.cat_deleted == false"
            ></i>
            <i class="el-icon-error" style="color: red" v-else></i>
          </template>
          <!-- </el-table-column> -->
          <!-- <el-table-column prop="cat_level" label="排序" width="200"> -->
          <template slot-scope="scope" slot="level">
            <el-tag v-if="scope.row.cat_level == '0'">一级</el-tag>
            <el-tag type="success" v-else-if="scope.row.cat_level == '1'"
              >二级</el-tag
            >
            <el-tag type="warning" v-else>三级</el-tag>
          </template>
          <!-- </el-table-column> -->

          <!-- <el-table-column label="操作" width="210"> -->
          <template slot-scope="scope" slot="operation">
            <div class="operation">
              <!--  slot-scope="scope" -->
              <!-- <el-row class="el-row"> -->
              <!-- <div class="bottomTip"> -->
              <el-button type="primary" icon="el-icon-edit" size="small"
              @click="showEditDialog(scope.row.cat_id)"
                >编辑</el-button
              >
              <!-- </div> -->

              <!-- <div class="bottomTip"> -->
              <el-button type="danger" icon="el-icon-delete" size="small"
              @click="showDeleteCate(scope.row.cat_id)"
                >删除</el-button
              >
              <!-- </div> -->
              <!-- </el-row> -->
            </div>
          </template>
          <!-- </el-table-column> -->
        </tree-table>
      </template>

      <div class="bottom">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[3, 5, 10, 15]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加分类 -->
    <el-dialog title="添加分类" :visible.sync="addDialogVisible" width="60%"
    @close="closeAddDialog">
      <el-form
        ref="addRuleForm"
        :model="addCategoryForm"
        label-width="100px"
        :rules="addRules"
      >
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="addCategoryForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类：" class="cate-item">
          <!-- 级联选择框 -->
          <el-cascader
            :options="twoLevelList"
            :props="levelProps"
            clearable
            expand-trigger="hover"
            @change="selectLevel"
            v-model="selectedKeys"
            change-on-select="true"
          ></el-cascader>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCategory">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑分类 -->
    <el-dialog
      title="编辑分类"
      :visible.sync="editDialogVisible"
      width="60%"
      @close="closeEdit"
    >
       <el-form
        ref="editRuleForm"
        :model="editForm"
        label-width="122px"
        :rules="addRules"
      >
        <el-form-item label="修改分类名称：" prop="cat_name">
          <el-input v-model="editForm.cat_name"></el-input>
        </el-form-item>
       </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCategory"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 删除分类 -->
    <el-dialog title="提示" :visible.sync="delCateVisible" width="30%">
      <span>是否删除该分类？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="delCateVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteCate">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "Categories",
  data() {
    return {
      searchInput: "",
      value: true,
      pageValue: "",

      // 分类列表
      categoryList: [],
      // 当前页面
      pageNum: 1,
      // 每页显示多少条数据
      pagesize: 5,
      // 数据总数
      total: 0,

      // 为树形table指定列的定义
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          label: "是否有效",
          // 当前列为模板列
          type: "template",
          // 当前这一列使用模板名称
          template: "isok",
        },
        {
          label: "排序",
          type: "template",
          template: "level",
        },
        {
          label: "操作",
          type: "template",
          template: "operation",
        },
      ],

      // 是否打开添加分类的对话框
      addDialogVisible: false,
      //  添加分类信息
      addCategoryForm: {
        cat_name: "",
        // 父级分类id
        cat_pid: 0,
        // 分类等级，默认一级分类
        cat_level: 0,
      },
      // 表单验证
      addRules: {
        cat_name: [
          {
            required: true,
            message: "分类名称不能为空！",
            trigger: "blur",
          },
        ],
      },
      twoLevelList: [],
      // 指定级联选择器的配置对象
      levelProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      // 选中的父级分类的id数组
      selectedKeys: [],

      // 是否展示编辑分类的对话框
      editDialogVisible:false,
      editForm:{
        cat_name:''
      },
      cat_id: '',
      
      // 是否展示删除分类的对话框
      delCateVisible:false
    };
  },
  created() {
    this.getCategoryData();
    // this.getTwoLevelData();
  },
  methods: {
    // 获取分类列表的数据
    getCategoryData() {
      this.axios({
        method: "get",
        url: "categories",
        params: {
          type: [1, 2, 3],
          pagenum: this.pageNum,
          pagesize: this.pagesize,
        },
      })
        .then((res) => {
          
          if (res.data.meta.status == 200) {
            this.categoryList = res.data.data;
            
            this.total = this.categoryList.total;
          }
        })
        .catch((err) => {
          
        });
    },
    // 底部页面选择
    handleSizeChange(val) {
      // 每页选择显示几条数据
      this.pagesize = val;
      this.getCategoryData();
    },
    handleCurrentChange(val) {
      // 当前页
      this.pageNum = val;
      this.getCategoryData();
    },

    // 打开添加分类的对话框
    showAddDialog() {
      this.addDialogVisible = true;
      this.getTwoLevelData();
    },

    // 关闭添加分类对话框时清空输入框
    closeAddDialog(){
      this.$refs.addRuleForm.resetFields();
    },

    // 获取分类列表的2级数据
    getTwoLevelData() {
      this.axios({
        method: "get",
        url: "categories",
        params: {
          type: 2,
        },
      })
        .then((res) => {
          
          if (res.data.meta.status == 200) {
            this.twoLevelList = res.data.data;
            
          }
        })
        .catch((err) => {
          
        });
    },

    // 选项发生变化时触发
    selectLevel() {
      

      // 若selectedKeys数组长度>0，则已选中父级分类
      // 反之，则没有选中任何父级分类
      if (this.selectedKeys.length > 0) {
        let parent = this.selectedKeys[this.selectedKeys.length - 1];
        // 分类父id
        this.addCategoryForm.cat_pid = parent;
        // 分类层级
        // selectedKeys长度为1时，代表选中父级分类
        // selectedKeys长度为2时，代表选中二级分类
        this.addCategoryForm.cat_level = this.selectedKeys.length;
        return;
      } else {
        this.addCategoryForm.cat_pid = 0;
        this.addCategoryForm.cat_level = 0;
      }
    },

    // 添加分类
    addCategory() {
      this.$refs.addRuleForm.validate(async (valid) => {
        

        if (valid) {
          this.axios({
            method: "post",
            url: "categories",
            data: {
              cat_pid: this.addCategoryForm.cat_pid,
              cat_name: this.addCategoryForm.cat_name,
              cat_level: this.addCategoryForm.cat_level,
            },
          })
            .then((res) => {
              
              if (res.data.meta.status == 201) {
                this.$message.success("添加分类成功！");
                this.addDialogVisible = false;
                this.getCategoryData();
                // 清除对话框
                this.addCategoryForm.cat_name = "";
              }
            })
            .catch((err) => {
              
            });
        } else {
          
          return false;
        }
      });
    },

    // 根据id查询分类
    search() {
      this.axios({
        method: "get",
        // url:'categories/:id'
        url: `categories/${this.searchInput}`,
      })
        .then((res) => {
          
          if (res.data.meta.status == 200) {
            this.$message.success("查询成功！");
          } else {
            this.$message.error("抱歉！查无此分类！");
          }
        })
        .catch((err) => {
          
        });
    },

    // 展示编辑分类的对话框
    showEditDialog(cat_id){
      
      this.editDialogVisible = true;

      this.cat_id = cat_id;
    },

    // 编辑分类
    editCategory(){
      

      this.$refs.editRuleForm.validate(async (valid) => {
        // 

        if (valid) {
          this.axios({
            method: "put",
            // url: "categories/:id",
            url: `categories/${this.cat_id}`,
            data: {
              cat_name: this.editForm.cat_name,
            },
          })
            .then((res) => {
              
              if (res.data.meta.status == 200) {
                this.$message.success("修改分类成功！");
                this.editDialogVisible = false;
                this.getCategoryData();
                // 清除对话框
                this.editForm.cat_name = "";
              }
            })
            .catch((err) => {
              
            });
        } else {
          
          return false;
        }
      });
    },

    closeEdit(){
      this.$refs.editRuleForm.resetFields();
    },

    // 展示删除分类的对话框
    showDeleteCate(cat_id){
      this.delCateVisible = true;

      
      this.cat_id = cat_id;
    },
    // 删除分类
    deleteCate(){
      
      this.axios({
        method:'delete',
        url: `categories/${this.cat_id}`,

      }).then(res=>{
        
        if(res.data.meta.status == 200){
          this.$message.success('删除成功！');
          this.delCateVisible = false;
          this.getCategoryData();
        }else{
          this.$message.error('删除失败！');
          return;
        }
      }).catch(err=>{
        
      })
    }
  },
};
</script>

<style lang="less" scoped>
.categories {
  margin-top: 70px;
  // background-color: #fff;
}

.box-card {
  margin-top: 22px;

  .top {
    display: flex;
    margin-bottom: 16px;
    .search-content {
      display: flex;
    }
    .add-user {
      margin-left: 18px;
    }
    /deep/ .el-input__inner {
      // border: 1px solid #000;
      border-top-right-radius: 0;
      border-bottom-right-radius: 0;
      outline: none;
    }
    /deep/ .search-icon {
      border-top-left-radius: 0;
      border-bottom-left-radius: 0;
      background-color: #ccc;
      border-color: #ccc;
    }
  }
  .bottom {
    margin-top: 15px;
  }

  /deep/ tbody .cell {
    font-size: 12px;
  }
}
.el-row {
  // border: 1px solid #000;
  display: flex;
  .bottomTip {
    margin-right: 10px;
  }
}
.operation {
  // border: 1px solid #000;
  display: flex;
}
.el-cascader {
  width: 100%;
}
.cate-item {
  // border: 1px solid #000;
  margin-top: 36px;
}
</style>

<style>
.el-scrollbar {
  /* border: 1px solid red; */
  height: 200px !important;
}
</style>